// 学生管理类 - 简约设计
class StudentManager {
    constructor() {
        this.students = [];
        this.currentPage = 1;
        this.pageSize = 8;
        this.filteredStudents = [];
        this.init();
    }

    // 初始化
    async init() {
        await this.loadFromAPI();
        this.bindEvents();
        this.renderStudents();
        this.updatePagination();
    }

    // 通过API加载学生数据
    async loadFromAPI() {
        try {
            const res = await fetch('http://localhost:3000/api/students');
            const data = await res.json();
            this.students = data;
            this.filteredStudents = [...data];
        } catch (e) {
            this.students = [];
            this.filteredStudents = [];
        }
    }

    // 保存学生数据到API
    async saveToAPI() {
        await fetch('http://localhost:3000/api/students', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(this.students)
        });
    }

    // 绑定事件
    bindEvents() {
        // 搜索功能
        const searchInput = document.querySelector('input[placeholder="搜索学生姓名/学号"]');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchStudents(e.target.value);
            });
        }

        // 添加学生按钮
        const addButton = document.querySelector('button:has(i.fa-plus)');
        if (addButton) {
            addButton.addEventListener('click', () => {
                this.showAddStudentModal();
            });
        }

        // 导出按钮
        const exportButton = document.querySelector('button:has(i.fa-download)');
        if (exportButton) {
            exportButton.addEventListener('click', () => {
                this.exportStudents();
            });
        }

        // 分页按钮
        this.bindPaginationEvents();
    }

    // 搜索学生
    searchStudents(keyword) {
        if (!keyword.trim()) {
            this.filteredStudents = [...this.students];
        } else {
            this.filteredStudents = this.students.filter(student => 
                student.name.includes(keyword) || 
                student.id.includes(keyword) ||
                student.department.includes(keyword) ||
                student.major.includes(keyword)
            );
        }
        this.currentPage = 1;
        this.renderStudents();
        this.updatePagination();
    }

    // 渲染学生列表 - 简约设计
    renderStudents() {
        const tbody = document.querySelector('tbody');
        if (!tbody) return;

        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageStudents = this.filteredStudents.slice(startIndex, endIndex);

        tbody.innerHTML = pageStudents.map(student => `
            <tr class="hover:bg-gray-50 transition-colors duration-200">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${student.id}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">${student.name}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${student.department}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${student.major}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${student.grade}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    <span class="font-semibold ${this.getCreditColor(student.credits)}">${student.credits}</span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                    <button class="text-blue-600 hover:text-blue-800" onclick="studentManager.viewStudent('${student.id}')">
                        <i class="fas fa-eye mr-1"></i>查看
                    </button>
                    <button class="text-blue-600 hover:text-blue-800" onclick="studentManager.editStudent('${student.id}')">
                        <i class="fas fa-edit mr-1"></i>编辑
                    </button>
                    <button class="text-red-600 hover:text-red-800" onclick="studentManager.deleteStudent('${student.id}')">
                        <i class="fas fa-trash mr-1"></i>删除
                    </button>
                </td>
            </tr>
        `).join('');
    }

    // 获取学分颜色
    getCreditColor(credits) {
        if (credits >= 8) return 'text-green-600';
        if (credits >= 6) return 'text-blue-600';
        if (credits >= 4) return 'text-yellow-600';
        return 'text-red-600';
    }

    // 更新分页 - 简约设计
    updatePagination() {
        const totalPages = Math.ceil(this.filteredStudents.length / this.pageSize);
        const paginationContainer = document.querySelector('.relative.z-0.inline-flex');
        if (!paginationContainer) return;

        // 更新分页信息
        const infoElement = document.querySelector('.text-sm.text-gray-700');
        if (infoElement) {
            const start = (this.currentPage - 1) * this.pageSize + 1;
            const end = Math.min(this.currentPage * this.pageSize, this.filteredStudents.length);
            infoElement.innerHTML = `
                显示第 <span class="font-medium">${start}</span> 到 <span class="font-medium">${end}</span> 条，共 <span class="font-medium">${this.filteredStudents.length}</span> 条记录
            `;
        }

        // 更新分页按钮
        this.renderPaginationButtons(totalPages);
    }

    // 渲染分页按钮 - 简约设计
    renderPaginationButtons(totalPages) {
        const paginationContainer = document.querySelector('.relative.z-0.inline-flex');
        if (!paginationContainer) return;

        let buttons = `
            <button class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${this.currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}" onclick="studentManager.goToPage(${this.currentPage - 1})">
                <i class="fas fa-chevron-left"></i>
            </button>
        `;

        for (let i = 1; i <= totalPages; i++) {
            if (i <= 5 || i === totalPages || (i >= this.currentPage - 2 && i <= this.currentPage + 2)) {
                buttons += `
                    <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium ${i === this.currentPage ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}" onclick="studentManager.goToPage(${i})">
                        ${i}
                    </button>
                `;
            } else if (i === this.currentPage - 3 || i === this.currentPage + 3) {
                buttons += `
                    <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                        ...
                    </span>
                `;
            }
        }

        buttons += `
            <button class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${this.currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}" onclick="studentManager.goToPage(${this.currentPage + 1})">
                <i class="fas fa-chevron-right"></i>
            </button>
        `;

        paginationContainer.innerHTML = buttons;
    }

    // 绑定分页事件
    bindPaginationEvents() {
        // 分页事件在 renderPaginationButtons 中通过 onclick 绑定
    }

    // 跳转到指定页面
    goToPage(page) {
        const totalPages = Math.ceil(this.filteredStudents.length / this.pageSize);
        if (page < 1 || page > totalPages) return;
        
        this.currentPage = page;
        this.renderStudents();
        this.updatePagination();
    }

    // 查看学生详情 - 简约设计
    viewStudent(studentId) {
        const student = this.students.find(s => s.id === studentId);
        if (student) {
            this.showStudentModal(student, 'view');
        }
    }

    // 编辑学生信息 - 简约设计
    editStudent(studentId) {
        const student = this.students.find(s => s.id === studentId);
        if (student) {
            this.showStudentModal(student, 'edit');
        }
    }

    // 删除学生
    async deleteStudent(studentId) {
        if (confirm('确定要删除这个学生吗？')) {
            this.students = this.students.filter(s => s.id !== studentId);
            this.filteredStudents = this.filteredStudents.filter(s => s.id !== studentId);
            await this.saveToAPI();
            this.renderStudents();
            this.updatePagination();
            this.showNotification('学生删除成功！', 'success');
        }
    }

    // 显示添加学生模态框
    showAddStudentModal() {
        this.showStudentModal(null, 'add');
    }

    // 显示学生模态框 - 简约设计
    showStudentModal(student, mode) {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        
        const title = mode === 'add' ? '添加学生' : mode === 'edit' ? '编辑学生' : '学生详情';
        const isView = mode === 'view';
        
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-lg max-w-md w-full mx-4">
                <div class="bg-gray-50 px-6 py-4 rounded-t-lg border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">${title}</h3>
                </div>
                <div class="p-6">
                    <form id="studentForm">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">学号</label>
                                <input type="text" name="id" value="${student?.id || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
                                <input type="text" name="name" value="${student?.name || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">院系</label>
                                <input type="text" name="department" value="${student?.department || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">专业</label>
                                <input type="text" name="major" value="${student?.major || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">年级</label>
                                <input type="text" name="grade" value="${student?.grade || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">学分</label>
                                <input type="number" step="0.1" name="credits" value="${student?.credits || ''}" ${isView ? 'readonly' : ''} class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="bg-gray-50 px-6 py-4 rounded-b-lg flex justify-end space-x-3">
                    <button onclick="this.closest('.fixed').remove()" class="px-4 py-2 text-gray-600 hover:text-gray-800">
                        取消
                    </button>
                    ${!isView ? `<button onclick="studentManager.saveStudent('${mode}')" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        ${mode === 'add' ? '添加' : '保存'}
                    </button>` : ''}
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    }

    // 保存学生信息
    async saveStudent(mode) {
        const form = document.getElementById('studentForm');
        const formData = new FormData(form);
        const studentData = Object.fromEntries(formData);
        if (mode === 'add') {
            this.students.push(studentData);
            this.filteredStudents = [...this.students];
            this.showNotification('学生添加成功！', 'success');
        } else if (mode === 'edit') {
            const index = this.students.findIndex(s => s.id === studentData.id);
            if (index !== -1) {
                this.students[index] = studentData;
                this.filteredStudents = [...this.students];
                this.showNotification('学生信息更新成功！', 'success');
            }
        }
        await this.saveToAPI();
        this.renderStudents();
        this.updatePagination();
        document.querySelector('.fixed').remove();
    }

    // 获取预警学生列表
    getWarningStudents() {
        return this.students.filter(student => student.credits < 4.0);
    }

    // 显示批量通知对话框
    showBatchNotificationDialog() {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full mx-4">
                <div class="bg-gray-50 px-6 py-4 rounded-t-lg border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">批量发送通知</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">接收学生筛选</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="checkbox" value="danger" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">严重警告学生</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" value="warning" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">一般警告学生</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" value="info" checked class="rounded text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">提醒通知学生</span>
                                </label>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">通知模板</label>
                            <div class="flex space-x-2">
                                <select id="notificationTemplate" class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="default">默认通知</option>
                                    <option value="deadline">截止日期提醒</option>
                                    <option value="activity">活动参与邀请</option>
                                </select>
                                <button id="saveTemplateBtn" class="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 text-sm" onclick="studentManager.saveNotificationTemplate()">
                                    保存模板
                                </button>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">自定义消息</label>
                            <textarea id="notificationMessage" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入通知内容...">
[学生姓名] 同学，您当前的第二课堂素质拓展学分进度为 [已获学分] 分。请及时参与相关活动以满足毕业要求。

系统自动发送，请勿回复。</textarea>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 rounded-b-lg flex justify-end space-x-3">
                    <button onclick="this.closest('.fixed').remove()" class="px-4 py-2 text-gray-600 hover:text-gray-800">
                        取消
                    </button>
                    <button onclick="studentManager.sendBatchNotifications()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        发送通知
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    }

    // 发送批量通知
    sendBatchNotifications() {
        const selectedLevels = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(cb => cb.value);
        const message = document.getElementById('notificationMessage').value;
        
        // 关闭对话框
        document.querySelector('.fixed').remove();
        
        // 获取符合条件的学生
        let students = this.filteredStudents || this.students;
        students = students.filter(student => { const level = this.getWarningLevel(student.credits); return level && selectedLevels.includes(level); });
        
        if (students.length === 0) {
            this.showNotification('没有符合条件的学生可发送通知', 'warning');
            return;
        }
        
        // 发送通知并跟踪状态
        const results = {
            success: 0,
            failed: 0,
            failedStudents: []
        };
        
        students.forEach(student => {
            try {
                // 替换消息中的变量
                let personalizedMessage = message
                    .replace(/\[学生姓名\]/g, student.name)
                    .replace(/\[已获学分\]/g, student.credits);
                
                // 模拟发送通知
                this.sendNotification(student.id, personalizedMessage);
                
                // 更新最后通知时间
                student.lastNotified = new Date().toISOString().split('T')[0];
                results.success++;
            } catch (error) {
                results.failed++;
                results.failedStudents.push(student.name);
            }
        });
        
        // 显示发送结果
        let resultMessage = `成功发送 ${results.success} 条通知`;
        if (results.failed > 0) {
            resultMessage += `，失败 ${results.failed} 条（${results.failedStudents.join('、')}）`;
        }
        this.showNotification(resultMessage, results.failed > 0 ? 'warning' : 'success');
    }

    // 导出学生名单为CSV
    exportStudents() {
        // 构建CSV内容
        let csvContent = '学号,姓名,院系,专业,年级,学分\n';
        this.filteredStudents.forEach(student => {
            csvContent += `${student.id},${student.name},${student.department},${student.major},${student.grade},${student.credits}\n`;
        });

        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `学生名单_${new Date().toLocaleDateString()}.csv`);
        link.style.visibility = 'hidden';

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.showNotification('学生名单导出成功！', 'success');
    }

    // 保存通知模板
    saveNotificationTemplate() {
        const templateSelect = document.getElementById('notificationTemplate');
        const templateName = templateSelect.options[templateSelect.selectedIndex].text;
        const message = document.getElementById('notificationMessage').value;

        // 从localStorage获取现有模板
        let templates = JSON.parse(localStorage.getItem('notificationTemplates') || '{}');
        templates[templateSelect.value] = { name: templateName, content: message };

        // 保存到localStorage
        localStorage.setItem('notificationTemplates', JSON.stringify(templates));
        this.showNotification('通知模板保存成功！', 'success');
    }

    // 发送单个通知
    sendNotification(studentId, message) {
        // 实际项目中这里会调用后端API或第三方服务发送通知
        // 这里仅做模拟
        console.log(`向学生 ${studentId} 发送通知:`, message);
        
        // 模拟网络请求延迟
        return new Promise(resolve => {
            setTimeout(() => resolve(true), 100);
        });
    }

    // 格式化警示等级文本
    getWarningLevelText(level) {
        switch(level) {
            case 'danger': return '严重警告';
            case 'warning': return '一般警告';
            case 'info': return '提醒通知';
            default: return '未设置';
        }
    }

    // 获取警示等级
    getWarningLevel(credits) {
        if (credits < 2) return 'danger';
        if (credits < 4) return 'warning';
        if (credits < 6) return 'info';
        return null;
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-md shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500 text-white' :
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'warning' ? 'bg-yellow-500 text-white' :
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 导出学生管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = StudentManager;
}